<?php
class SiteController extends Controller
{
	private $nsDownload = 'ATTACHMENT_DOWNLOADS';
	
	public function init()
	{
		parent::init();
	}
	
	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionIndex()
	{
		
		/*get latest documents*/
		$arrDocuments = Posts::getInstance()->getList(array(
			'taxonomy_id' => 2,
			'post_status' => 1,		
			'page' => 1,
			'limit' => 5,
		));
		foreach($arrDocuments as &$R){
			$R['post_category'] = Posts::getInstance()->getCategories($R['post_id']);
		}
		$this->render('index', array(
			'arrDocuments' => $arrDocuments
		));
	}

	public function actionDocuments()
	{
		/*check if logined*/
		if (Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->createUrl('auth/login', array('url'=>urlencode(Utils::getCurrentUrl()))));
		}
		
		/*get params*/		
		$intRowsPerPage = DEFAULT_ROWS_PER_PAGE;
		$intPage = Yii::app()->request->getParam('page', 1);
		$cateId = Yii::app()->request->getParam('cateId', null);
		$keyword = Yii::app()->request->getParam('q', null);
		if(!empty($keyword)) $keyword = '%'.$keyword.'%';		
		
		/*cate detail*/
		$cate = array();
		if(!empty($cateId)){
			$cate = Categories::getInstance()->get($cateId);
			//wrong cate id
			if(empty($cate)){
				$this->redirect('/error.html');
			}
		}
		
		if(Yii::app()->request->getParam('latest-laws')){
			$latest_laws_cates = Categories::getInstance()->getByParent(array('category_parent' => 55, 'category_status' => 1));
			$latest_laws_ids = array(55);
			foreach($latest_laws_cates as $R){
				$latest_laws_ids[] = $R['category_id'];
			}
			$latest_laws_ids = implode(',', $latest_laws_ids);
			/*search latest laws*/
			$arrDocuments = Posts::getInstance()->getList(array(
				'taxonomy_id' => 2,
				'post_status' => 1,	
				'keyword' => null,
				'category_id' => $latest_laws_ids,
				'post_created_date_from' => date('Y-m-d', mktime()-60*60*24*30),
				'page' => $intPage,
				'limit' => $intRowsPerPage,
			));
		} else {
			/*get list documents*/
			$arrDocuments = Posts::getInstance()->getList(array(
				'taxonomy_id' => 2,
				'post_status' => 1,	
				'keyword' => $keyword,
				'category_id' => $cateId,
				'page' => $intPage,
				'limit' => $intRowsPerPage,
			));
		}
		$intTotalRows = isset($arrDocuments[0]['total_rows'])?$arrDocuments[0]['total_rows']:0;
		foreach($arrDocuments as &$R){
			$R['post_category'] = Posts::getInstance()->getCategories($R['post_id']);
		}
		
		/*get document folders*/
		$arrFolders = HelpDesk::getInstance()->getDocumentFolders();
		
		//paging
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		$this->render('documents/documents', array(
			'arrFolders' => $arrFolders,
			'arrDocuments' => $arrDocuments,
			'keyword' => trim($keyword, '%'),
			'objPages' => $objPages,
			'cateId' => $cateId,
			'cate' => $cate,
			'latest_laws'=>Yii::app()->request->getParam('latest-laws')
		));
	}
	
	public function actionViewDocument()
	{
		/*check if logined*/
		if (Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->createUrl('auth/login', array('url'=>urlencode(Utils::getCurrentUrl()))));
		}
		
		$cateId = Yii::app()->request->getParam('cateId', null);

		/*get document folders*/
		$arrFolders =HelpDesk::getInstance()->getDocumentFolders();
		
		/*get post detail*/
		$post = array();
		$postId = Yii::app()->request->getParam('postId', null);
		if(!empty($postId)){
			$post = Posts::getInstance()->get($postId);				
		}
		if(empty($post) || $post['post_status'] != '1'){
			$this->redirect('/error.html');
		}
		
		/*prepare download file*/
		$urlDownload = '';
		if(isset($post['fields']['article-attachment']) && $post['post_privacy'] == '2'){
			$token = Utils::generateToken($this->nsDownload);
			$token = base64_encode($post['post_id'].'-'.$token);
			$urlDownload = "/download/{$token}.html";
		}
		
		/*cate detail*/
		$cate = array();
		if(!empty($cateId)){
			$cate = Categories::getInstance()->get($cateId);
		}
		
		$this->render('documents/view-document', array(
			'arrFolders' => $arrFolders,
			'post' => $post,
			'cateId' => $cateId,
			'cate' => $cate,
			'urlDownload' => $urlDownload,
			'tokenDownload' => $token
		));
	}

	public function actionFAQs()
	{
		/*check if logined*/
		if (Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->createUrl('auth/login', array('url'=>urlencode(Utils::getCurrentUrl()))));
		}
		
		/*get params*/
		$intRowsPerPage = DEFAULT_ROWS_PER_PAGE;
		$intPage = Yii::app()->request->getParam('page', 1);
		$cateId = Yii::app()->request->getParam('cateId', null);
		$keyword = Yii::app()->request->getParam('q', null);
		if(!empty($keyword)) $keyword = '%'.$keyword.'%';	
		
		$arrFaqs = Posts::getInstance()->getList(array(
			'taxonomy_id' => 3,
			'keyword' => $keyword,
			'category_id' => $cateId,
			'post_status' => 1,				
			'page' => $intPage,
			'limit' => $intRowsPerPage,
			'order' => 'ASC'
		));
		$intTotalRows = isset($arrFaqs[0]['total_rows'])?$arrFaqs[0]['total_rows']:0;
		
		/*get folder section*/
		$arrFolders = HelpDesk::getInstance()->getFAQFolders();
		
		/*cate detail*/
		$cate = array();
		if(!empty($cateId)){
			$cate = Categories::getInstance()->get($cateId);
		}
		
		//paging
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		$this->render('faqs', array(
			'arrFaqs' => $arrFaqs,
			'keyword' => trim($keyword, '%'),
			'arrFolders' => $arrFolders,
			'objPages' => $objPages,
			'cateId' => $cateId,
			'cate' => $cate
		));	
	}

	public function actionDownload()
	{
		try{
			/*check if logined*/
			if (Yii::app()->user->isGuest){
				$this->redirect(Yii::app()->createUrl('auth/login', array('url'=>urlencode(Utils::getCurrentUrl()))));
			}
			/*decode token*/
			$rawToken = Yii::app()->request->getParam('token', null);
			$token = base64_decode($rawToken, true);
			if(empty($token)){
				$this->redirect('/error.html');
			}
			/*validate token*/
			$token = explode('-', $token);
			$validToken = Utils::verifyToken($this->nsDownload, $token[1], false, false);
			if(!$validToken){
				$this->redirect('/error.html');
			}
			/*validate post*/
			$post = Posts::getInstance()->get($token[0]);
			if(empty($post) || $post['post_status'] != '1' || empty($post['fields']['article-attachment']) || $post['post_privacy'] != '2'){
				$this->redirect('/error.html');
			}			
			/*download*/
			$file = UPLOADS_DIR.'/'.$post['fields']['article-attachment'];
			if(!is_file($file)){
				$this->redirect('/error.html');
			}
			$fileSize = filesize($file);
			// If it's a large file, readfile might not be able to do it in one go, so:
  			$chunksize = 1 * (2* 1024); // how many bytes per chunk
			
			header('Content-Type: application/octet-stream');
			header('Content-Length: ' . $fileSize); 
			header('Content-Disposition: attachment; filename=' . pathinfo($file, PATHINFO_BASENAME)); 
			ob_clean(); 
			flush(); 
			
			if ($fileSize > $chunksize) {
				$handle = fopen($file, 'rb');
				$buffer = '';
				while (!feof($handle)) {
					$buffer = fread($handle, $chunksize);
					// All you need is 256 spaces first
					echo $buffer;
					ob_flush();
					flush();
				}
				fclose($handle);
			} else {
				readfile($file);
			}
			
			/*write log*/
			Logs::getInstance()->insert(
				array(
					'user_id' => Yii::app()->user->id,
					'user_ip' => Utils::getIp(),
					'user_agent' => $_SERVER['HTTP_USER_AGENT'],
					'log_action' => 'HELPDESK_DOWNLOAD',
					'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b>'.' downloaded <b>'.pathinfo($post['fields']['article-attachment'], PATHINFO_BASENAME).'</b> in "<b>'.$post['post_title'].'</b>" with token <b>'.$rawToken.'</b>'
				)
			);
		} catch(Exception $ex){
			$this->redirect('/error.html');
		}
	}

	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		} else {
			$this->render('error', $error);
		}
	}

	
}